const { Note, NoteTag, NoteImage, User, Category, NoteCategory } = require('../models');
const { generateUniqueId } = require('../utils/authUtils');
const { validationResult } = require('express-validator');
const { Op } = require('sequelize');

// 创建笔记
const createNote = async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { title, content, tags = [], images = [], categoryIds = [] } = req.body;
    const userId = req.user.id;

    // 创建笔记
    const note = await Note.create({
      id: generateUniqueId(),
      title,
      content,
      user_id: userId,
      created_at: new Date()
    });

    // 创建标签
    if (tags.length > 0) {
      const tagPromises = tags.map(tag => 
        NoteTag.create({ note_id: note.id, tag })
      );
      await Promise.all(tagPromises);
    }

    // 创建图片
    if (images.length > 0) {
      const imagePromises = images.map(imageUrl => 
        NoteImage.create({ note_id: note.id, image_url: imageUrl })
      );
      await Promise.all(imagePromises);
    }

    // 关联分类
    if (categoryIds.length > 0) {
      const categoryPromises = categoryIds.map(categoryId => 
        NoteCategory.create({ note_id: note.id, category_id: categoryId })
      );
      await Promise.all(categoryPromises);
    }

    res.status(201).json({ message: '笔记创建成功', noteId: note.id });
  } catch (error) {
    console.error('创建笔记失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取笔记列表
const getNotes = async (req, res) => {
  try {
    const { page = 1, limit = 10, search = '', categoryId = '', userId = '' } = req.query;
    
    const offset = (page - 1) * limit;
    
    const where = {};
    if (search) {
      where[Op.or] = [
        { title: { [Op.like]: `%${search}%` } },
        { content: { [Op.like]: `%${search}%` } }
      ];
    }
    if (userId) {
      where.user_id = userId;
    }

    const include = [
      { model: User, attributes: ['id', 'username', 'avatar'] },
      { model: NoteTag, attributes: ['tag'] },
      { model: NoteImage, attributes: ['image_url'] }
    ];

    // 如果指定了分类，需要通过关联表查询
    if (categoryId) {
      include.push({
        model: NoteCategory,
        where: { category_id: categoryId }
      });
    } else {
      include.push({ model: Category, through: NoteCategory });
    }

    const { count, rows: notes } = await Note.findAndCountAll({
      where,
      include,
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['created_at', 'DESC']]
    });

    const formattedNotes = notes.map(note => ({
      id: note.id,
      title: note.title,
      content: note.content,
      user: {
        id: note.User.id,
        username: note.User.username,
        avatar: note.User.avatar
      },
      tags: note.NoteTags.map(tag => tag.tag),
      images: note.NoteImages.map(image => image.image_url),
      categories: note.Categories?.map(cat => ({ id: cat.id, name: cat.name })) || [],
      likes: note.likes,
      comments: note.comments,
      created_at: note.created_at
    }));

    res.status(200).json({
      notes: formattedNotes,
      total: count,
      page: parseInt(page),
      limit: parseInt(limit),
      totalPages: Math.ceil(count / limit)
    });
  } catch (error) {
    console.error('获取笔记列表失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取单个笔记
const getNoteById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const note = await Note.findByPk(id, {
      include: [
        { model: User, attributes: ['id', 'username', 'avatar'] },
        { model: NoteTag, attributes: ['tag'] },
        { model: NoteImage, attributes: ['image_url'] },
        { model: Category, through: NoteCategory }
      ]
    });
    
    if (!note) {
      return res.status(404).json({ message: '笔记不存在' });
    }

    const formattedNote = {
      id: note.id,
      title: note.title,
      content: note.content,
      user: {
        id: note.User.id,
        username: note.User.username,
        avatar: note.User.avatar
      },
      tags: note.NoteTags.map(tag => tag.tag),
      images: note.NoteImages.map(image => image.image_url),
      categories: note.Categories.map(cat => ({ id: cat.id, name: cat.name })),
      likes: note.likes,
      comments: note.comments,
      created_at: note.created_at,
      updated_at: note.updated_at
    };

    res.status(200).json(formattedNote);
  } catch (error) {
    console.error('获取笔记详情失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 更新笔记
const updateNote = async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { id } = req.params;
    const { title, content, tags = [], images = [], categoryIds = [] } = req.body;
    const userId = req.user.id;

    // 查找笔记
    const note = await Note.findByPk(id);
    if (!note) {
      return res.status(404).json({ message: '笔记不存在' });
    }

    // 检查权限
    if (note.user_id !== userId) {
      return res.status(403).json({ message: '没有权限修改此笔记' });
    }

    // 更新笔记基本信息
    await note.update({ title, content });

    // 更新标签
    await NoteTag.destroy({ where: { note_id: id } });
    if (tags.length > 0) {
      const tagPromises = tags.map(tag => 
        NoteTag.create({ note_id: id, tag })
      );
      await Promise.all(tagPromises);
    }

    // 更新图片
    await NoteImage.destroy({ where: { note_id: id } });
    if (images.length > 0) {
      const imagePromises = images.map(imageUrl => 
        NoteImage.create({ note_id: id, image_url: imageUrl })
      );
      await Promise.all(imagePromises);
    }

    // 更新分类
    await NoteCategory.destroy({ where: { note_id: id } });
    if (categoryIds.length > 0) {
      const categoryPromises = categoryIds.map(categoryId => 
        NoteCategory.create({ note_id: id, category_id: categoryId })
      );
      await Promise.all(categoryPromises);
    }

    res.status(200).json({ message: '笔记更新成功' });
  } catch (error) {
    console.error('更新笔记失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 删除笔记
const deleteNote = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    // 查找笔记
    const note = await Note.findByPk(id);
    if (!note) {
      return res.status(404).json({ message: '笔记不存在' });
    }

    // 检查权限
    if (note.user_id !== userId) {
      return res.status(403).json({ message: '没有权限删除此笔记' });
    }

    // 删除笔记（会级联删除相关的标签、图片和分类关联）
    await note.destroy();

    res.status(200).json({ message: '笔记删除成功' });
  } catch (error) {
    console.error('删除笔记失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 管理员删除笔记
const adminDeleteNote = async (req, res) => {
  try {
    const { id } = req.params;

    // 查找笔记
    const note = await Note.findByPk(id);
    if (!note) {
      return res.status(404).json({ message: '笔记不存在' });
    }

    // 管理员可以直接删除
    await note.destroy();

    res.status(200).json({ message: '笔记删除成功' });
  } catch (error) {
    console.error('删除笔记失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

module.exports = {
  createNote,
  getNotes,
  getNoteById,
  updateNote,
  deleteNote,
  adminDeleteNote
};